<?php

namespace App\Http\Controllers;

use App\Exceptions\AppException;
use App\Exceptions\AuthException;
use App\Models\SheetTemplate;
use App\Models\Task;
use App\Models\TaskTemplate;
use App\Services\TaskService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class TaskTemplateController extends Controller
{
    public function create(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'frequency' => 'required|in:monthly,once',
            'sheet_template_id' => 'required|integer|exists:sheet_templates,id,type,' . SheetTemplate::TYPE_REPORT . ',deleted_at,NULL',
            'description' => 'required|string|max:100',
            'attachment' => 'nullable|array:url,name',
        ]);

        if (!Auth::user()->hasPermissionTo('task-template')) {
            throw new AuthException();
        }
        $exists = SheetTemplate::whereId($request->sheet_template_id)
            ->whereExists(function ($q) use ($request) {
                $q->select(\DB::raw(1))
                    ->from('sheet_pivot')
                    ->whereRaw('report_template_id = sheet_templates.id')
                    ->where('frequency', $request->frequency);
            })
            ->exists();
        if (!$exists) {
            throw new AppException('该模板没有符合条件的汇总周期');
        }
        $isCreated = TaskTemplate::where([
            'sheet_template_id' => $request->sheet_template_id,
            'frequency' => $request->frequency,
        ])
            ->exists();
        if ($isCreated) {
            throw new AppException('该模板已创建同周期任务');
        }
        DB::transaction(function () use ($validated, $request) {
            $taskTemplate = TaskTemplate::create($validated);
            Task::where(['sheet_template_id' => $request->sheet_template_id, 'frequency' => $request->frequency])
                ->update(['task_template_id' => $taskTemplate->id]);
        });
        return responder()->success();
    }

    public function list(Request $request)
    {
        $request->validate([
            'name' => 'nullable|string|max:50',
            'frequency' => 'nullable|in:monthly,once',
            'page' => 'nullable|integer|min:1',
            'per_page' => 'nullable|integer',
        ]);

        if (!Auth::user()->hasPermissionTo('task-template')) {
            throw new AuthException();
        }
        $query = TaskTemplate::with('sheetTemplate');
        if ($request->name) {
            $query->where('name', 'like', "%{$request->name}%");
        }
        if ($request->frequency) {
            $query->where('frequency', $request->frequency);
        }
        $res = $query->orderBy('id', 'desc')->paginate($request->per_page);
        return responder()->success($res);
    }

    public function show(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:task_templates,id,deleted_at,NULL',
        ]);

        if (!Auth::user()->hasPermissionTo('task-template')) {
            throw new AuthException();
        }
        $res = TaskTemplate::with('sheetTemplate')->find($request->id);
        return responder()->success($res);
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'id' => 'required|integer|exists:task_templates,id,deleted_at,NULL',
            'name' => 'required|string|max:50',
            'description' => 'required|string|max:255',
            'attachment' => 'nullable|array:url,name',
        ]);

        if (!Auth::user()->hasPermissionTo('task-template')) {
            throw new AuthException();
        }
        $model = TaskTemplate::find($request->id);
        if ($model->frequency == 'once' && $model->name != $validated['name']) {
            throw new AppException('一次性任务模板不能修改名称，请重新创建');
        }
        $model->update($validated);
        return responder()->success();
    }

    public function delete(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:task_templates,id,deleted_at,NULL',
        ]);

        if (!Auth::user()->hasPermissionTo('task-template')) {
            throw new AuthException();
        }
        $model = TaskTemplate::find($request->id);
        if ($model->tasks()->where('status', '!=', Task::STATUS_INITIALIZED)->exists()) {
            throw new AppException('该模板已被使用');
        }
        $model->delete();
        return responder()->success();
    }

    public function manualPublish(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:task_templates,id,deleted_at,NULL',
        ]);

        if (!Auth::user()->hasPermissionTo('task-template')) {
            throw new AuthException();
        }
        TaskService::create(TaskTemplate::find($request->id));
        return responder()->success();
    }
}
